const jsonParse = require('../../lib/jsonParse')
const Header = require('../../lib/getHeader');
const AreaMains = require('../../schemas/common').AreaMains
module.exports = {
    /**
     * 获取区域
     */
    async getAreaList(req, res) {
        AreaMains.find({delFlag: '0'}, {
            regionCode: 1,
            parentCode: 1,
            level: 1,
            regionName: 1,
            pinyin: 1
        }).then(area => {
            if (area && area.length) {
                let temp = area.sort((x, y) => (x.pinyin.localeCompare(y.pinyin)))
                const list = JSON.parse(JSON.stringify(temp))
                let province = list.filter(e => e.level == 1)
                module.exports.areaTree(list, province)
                jsonParse.sendResult(res, 200, province)
            }
        })
    },
    areaTree(allArea, areaList) {
        areaList.forEach(e => {
            e.children = []
            if (allArea.findIndex(o => o.parentCode == e.regionCode) != -1) {
                let arr = allArea.filter(o => o.parentCode == e.regionCode)
                e.children.push(...arr)
                module.exports.areaTree(allArea, e.children)
            } else {
                delete e.children
            }
        })
    }
}